package com.jumi.microservice.listener;

import com.jumi.microservice.common.context.SpringApplicationContext;
import com.jumi.microservice.domain.GoodsScheduleDTO;
import com.jumi.microservice.mapper.GoodsMapper;
import com.jumi.microservice.mapper.GoodsScheduleMapper;
import com.jumi.microservice.schedule.GoodsFixPuttedOnShelvesTask;
import com.jumi.microservice.service.GoodsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import java.time.ZoneId;
import java.util.Date;
import java.util.List;


/**
 * 系统初始化监听器(测试)
 *
 * @author Administrator
 */
public class SystemInitContextListenerTest implements ApplicationListener<ApplicationStartedEvent> {

    private static final Logger logger = LoggerFactory.getLogger(SystemInitContextListenerTest.class);

    @Autowired
    private SpringApplicationContext context;

    @Autowired
    private GoodsScheduleMapper goodsScheduleMapper;

    @Autowired
    private GoodsMapper goodsMapper;

    @Override
    public void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) {
        logger.info("【系统启动】系统已经完成系统");

        GoodsService goodsService = context.getBean(GoodsService.class);
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setPoolSize(10);
        taskScheduler.initialize(); // 务必调用此方法来启动

        while (true) {
            List<GoodsScheduleDTO> scheduleGoods = goodsService.getScheduleGoods();
            for (GoodsScheduleDTO goodsSchedule : scheduleGoods) {
                Date goodsSelltime = Date.from(goodsSchedule.getGoodsSelltime().atZone(ZoneId.systemDefault()).toInstant());
                taskScheduler.schedule(new GoodsFixPuttedOnShelvesTask(), goodsSelltime);
                goodsSchedule.setIsSchedule(1);
                goodsService.updateGoodsScheduleStatus(goodsSchedule);
            }
        }
    }

    @Bean
    public SchedulerFactoryBean schedulerFactoryBean() {
        return new SchedulerFactoryBean();
    }
}